package com.example.webwork.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.example.webwork.dto.AuthorArticleCount;
import com.example.webwork.entity.Article;
import com.example.webwork.entity.Contact;
import com.example.webwork.mapper.ArticleMapper;
import com.example.webwork.service.IArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("ArticleServiceImpl")
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements IArticleService {


    @Autowired
    private ArticleMapper articleMapper; // 🔥 这里注入！
    @Override
    public List<Article> getAllArticles(String username) {
        System.out.println(list(new QueryWrapper<Article>().eq("username",username)) );
        return list(new QueryWrapper<Article>().eq("username", username));
    }

    @Override
    public void addArticle(Article article) {
        save(article);
    }

    @Override
    public void updateArticle(Article article) {
        updateById(article);
    }

    @Override
    public void deleteArticle(Long id) {
        removeById(id);
    }

    //这里是用来返回全部的文章和user的统计列表
    @Override
    public List<AuthorArticleCount> getArticleCounts() {
//        List<Article> articleList = articleMapper.selectList(null);
//
//        //使用一个map统计username的count
//        Map<String,Integer> countMap=new HashMap<>();
//        for (Article article:articleList){
//            String username=article.getUsername();
//            countMap.put(username,countMap.getOrDefault(username,0)+1);
//        }
//        //把统计结果转换成List<AuthorArticleCount>
//        List<AuthorArticleCount> result=new ArrayList<>();
//        for(Map.Entry<String,Integer> entry:countMap.entrySet())
//        {
//            result.add(new AuthorArticleCount(entry.getKey(),entry.getValue()));
//        }
//        return result;
        return articleMapper.getAuthorArticleCount();
    }

    @Override
    public List<Article> searchArticles(String username, String name) {
        QueryWrapper<Article> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("username", username);
        if (name != null && !name.trim().isEmpty()) {
            queryWrapper.like("title", name);  // 模糊匹配
        };
return list(queryWrapper);
    }


}
